var attach = {
    instance: function () { //获取对象
        return this;
    },
    //格式化按钮,用于grid显示
    fomatBtn: function (value, row, index, model, gd) {
        var self = this;
        var btn = "";
        if (model == true) {
            btn += '<button type="button" class="btn btn-primary btn-sm" onclick="attach.deleteFile( ' + row.FileId + ',\'' + gd + '\')">删除</button>';
        }
        btn += '&nbsp;<a class="btn btn-primary btn-sm" href="#" onclick="attach.downLoad(\'' + row.FilePath + '\',\'' + row.OrgFileName + '\')" role="button">下载</a>';
        btn += '&nbsp;<a class="btn btn-primary btn-sm" href="#" onclick="attach.lookOnLine(\'' + row.FilePath + '\',' + row.FileId + ')" role="button">在线查看</a>';
        return btn;

    },
    //转换文件大小,用于grid显示
    fomatSize: function (value, row, index) {
        var self = this;
        var filesieze = 0;
        filesieze = row.FileSize;
        filesieze = filesieze / 1024 / 1024
        filesieze = filesieze.toFixed(3);
        return filesieze;
    },
    //加载数据loading提示
    ajaxLoading: function (msg) {
        $("<div id=\"divlaoding\" class=\"datagrid-mask\"></div>").css({
            display: "block",
            width: "100%",
            height: $(window).height()
        }).appendTo("body");
        $("<div id=\"divMsg\" class=\"datagrid-mask-msg\" style=\"height:auto\"></div>").html(msg).appendTo("body").css({
            display: "block",
            left: ($(document.body).outerWidth(true) - 190) / 2,
            top: ($(window).height() - 45) / 2
        });
    },
    //在线查看实现
    lookOnLine: function (FilePath, FileId) {

        var str = FilePath.split("\\");
        var api = frameElement.api;
        var fileT = str[str.length - 1].toLowerCase().split(".");
        var fileType = fileT[fileT.length - 1];

        var officeType = ["doc", "docx", "xls", "ppt", "xlsx", "pptx"];
        var ySType = ["zip", "rar", "7z"];

        if (FilePath == "") { //没有上传文件

            $.messager.alert("错误提示", "没有可在线查看的文件");
            return;
        }
        if ($.inArray(fileType, officeType) > -1) {
            $.messager.progress({
                msg: "文件加载中，请稍等...",
                interval: 300
            });
            //上传的文件为office文件
            $.post("../ZECSHandle.ashx?key=ConvertToImage&FileUrl=" + FilePath, function (data) {
                $.messager.progress('close');
                if (data.Result == "ERROR") {
                    $.messager.alert("提示信息", data.Message);
                    return;
                } else {

                    api.opener.$.dialog({
                        id: 'onlieBrowse',
                        content: 'url:viewer/Show.html',
                        lock: true,
                        data: {
                            imgArr: data.Records
                        },
                        title: '在线查看',
                        close: function () {
                            api.opener.$.dialog({
                                id: 'onlieBrowse'
                            });

                        }
                    }).max(); ;
                }
            });

        } else if ($.inArray(fileType, ySType) > -1) {

            $.messager.alert("错误提示", "压缩文件不支持在线查看，请下载解压查看！");
            return;
        } else {
            //其他格式的文件，直接打开
            api.opener.$.dialog({
                id: 'onlieBrowse',
                content: 'url:' + FilePath,
                lock: true,
                title: '在线查看',
                close: function () {
                    api.opener.$.dialog({
                        id: 'onlieBrowse'
                    });

                }
            }).max();
        }
    },
    //关闭loading提示
    ajaxLoadEnd: function () {
        $("#divlaoding").remove();
        $("#divMsg").remove();
    },
    htmlEncode: function (html) {
        return document.createElement('a').appendChild(
            document.createTextNode(html)).parentNode.innerHTML;
    },
    initFileList: function (element, fileIDArr) {
        //加载文件列表
        $(element).datagrid({
            singleSelect: true,
            url: "../BFSHandle.ashx?key=FileList&resultType=2",
            queryParams: {
                FileId: fileIDArr()
            }
        });

    },
    initUpload: function (model, element, fileIDArr) {
        var tbname = "gd_" + element.id;
        //初始化附件列表控件
        var FileList = $(
            "<table class=\"easyui-datagrid\" width=\"550\" id=" + tbname + ">" +
            "<thead>" +
            "    <tr>" +
            "        <th data-options=\"field:'Id',hidden:true\">Id</th>" +
            "        <th data-options=\"field:'OrgFileName',width:100\">文件名</th>" +
            "        <th data-options=\"field:'FileSize',width:100,formatter:function(value,row,index){return attach.fomatSize(value,row,index);}\" >文件大小(M)</th>" +
            "        <th data-options=\"field:'FilePath',width:100\">文件路径</th>" +
            "        <th data-options=\"field:'operator',width:220,formatter:function(value,row,index){return attach.fomatBtn(value,row,index," + model + ",'" + tbname + "');},align:'center'\">操作</th>" +
            "   </tr>" +
            "</thead>" +
            "</table>"
        );

        $(element).after(FileList);

        //编辑模式         
        if (model == true) {
            //生成上传文件控件
            setTimeout(function () {
                $(element).uploadify({
                    height: 30,
                    swf: '/Lib/Scripts/uploadify/uploadify.swf',
                    uploader: '../BFSHandle.ashx?key=FileUpload',
                    auto: true,
                    width: 110,
                    height: 35,
                    buttonText: "上传文件",
                    cancelImage: '/Lib/Scripts/uploadify/uploadify-cancel.png', //取消图片的路径
                    fileSizeLimit: '10MB', //文件的极限大小，以字节为单位，0为不限制。1MB:1*1024*1024

                    //每个文件上传成功都会触发
                    onUploadSuccess: function (file, data, response) {

                        var fileId = fileIDArr(); //获取文件ID 格式以逗号分隔 1，2，3，4
                        var fileArr; //上传文件ID数组
                        if (fileId != "" && fileId != null) {
                            fileArr = fileId.split(","); //把文件ID字符串转换成数组
                        } else {
                            fileArr = []; //创建空对象
                        }

                        var resultData = JSON.parse(data);
                        if (resultData.Result == 'OK') {

                            fileArr.push(resultData.Id); //新上传成功的文件ID加入数组
                            fileIDArr(fileArr.join(",")); //更新值                                

                        } else if (resultData.result == 'ERROR') {
                            $.messager.alert("提示信息", resultData.Message);
                        }

                    },
                    //所有文件上传成功后执行
                    onQueueComplete: function (stats) {
                        attach.initFileList(FileList, fileIDArr);
                    }

                });
            }, 10);
        }

        attach.initFileList(FileList, fileIDArr);

    },
    deleteFile: function (fielId, gd) {
        $.post("../BFSHandle.ashx?key=FileDelete", {
            FileId: fielId
        },
            function (data) {
                if (data.Result == "ERROR") {
                    $.messager.alert("提示信息", data.Message);
                    return;
                } else {
                    $("#" + gd).datagrid("reload");
                    $.messager.alert("提示信息", "删除成功!");
                }
            });
    },
    formatDate: function (date, format) {
        if (!date) return;
        if (!format) format = "yyyy-MM-dd HH:mm:ss";
        switch (typeof date) {
            case "string":
                if (date.indexOf("Date") > -1) {
                    var time = date.substring(date.indexOf("(") + 1, date.lastIndexOf(")"));
                    date = new Date(parseInt(time));
                    break;
                }

                date = new Date(date.replace(/-/g, "/"));
                break;
            case "number":
                date = new Date(date);
                break;
        }
        if (!date instanceof Date) return;

        var paddNum = function (num) {
            num += "";
            return num.replace(/^(\d)$/, "0$1");
        }
        //指定格式字符
        var cfg = {
            yyyy: date.getFullYear() //年 : 4位
                ,
            yy: date.getFullYear().toString().substring(2) //年 : 2位
                ,
            M: date.getMonth() + 1 //月 : 如果1位的时候不补0
                ,
            MM: paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
                ,
            d: date.getDate() //日 : 如果1位的时候不补0
                ,
            dd: paddNum(date.getDate()) //日 : 如果1位的时候补0
                ,
            H: date.getHours() //时
                ,
            HH: paddNum(date.getHours()) //时
                ,
            m: date.getMinutes() //分
                ,
            mm: paddNum(date.getMinutes()) //分
                ,
            s: date.getSeconds() //秒
                ,
            ss: paddNum(date.getSeconds()) //秒
        }
        format || (format = "yyyy-MM-dd HH:mm:ss");
        return format.replace(/([a-z])(\1)*/ig, function (m) {
            return cfg[m];
        });
    },
    //下载功能
    downLoad: function (url, fileName) {
        var $iframe = $("#TempCreatedIframeElement");
        if ($iframe == null || $iframe.length == 0) {
            $iframe = $("<iframe><iframe>");
            $iframe.attr("id", "TempCreatedIframeElement");
        }
        $iframe.css("display", "none");
        $iframe.attr("src", "../ZECSHandle.ashx?key=DownFile&FileUrl=" + url + "&FileName=" + fileName);
        $(document.body).append($iframe);
    }
};
